import json
import time
import requests
from lxml import etree

class jianshu:

    def __init__(self, UID):
        self.UID = UID
        if requests.get("http://www.jianshu.com/u/" + self.UID).status_code == 404:
            raise Exception("用户ID不存在")

    def info(self):
        html = etree.HTML(requests.get("http://www.jianshu.com/u/" + self.UID).text)
        info = {
            "name": html.xpath('//a[@class="name"]')[0].text,
            "avatar": html.xpath('//a[@class="avatar"]/img')[0].attrib["src"],
            "description": html.xpath('//div[@class="js-intro"]')[0].text
        }
        return info

    def article(self, page=1, type="u", id=None):
        if type == "u":
            r = requests.get("http://www.jianshu.com/u/" + self.UID + "?page=%s" % page)
        elif type == "nb":
            r = requests.get("http://www.jianshu.com/nb/" + str(id) + "?page=%s" % page)
        if (r.status_code == 404) or (r.status_code == 302):
            return None
        html = etree.HTML(r.text)
        articles = []
        try:
            for a in html.xpath('//ul[@class="note-list"]/li'):
                if a.xpath('.//a[@class="wrap-img"]'):
                    img = a.xpath('.//a[@class="wrap-img"]/img')[0].attrib["src"]
                else:
                    img = "http://obqk5qqck.bkt.clouddn.com/default.jpg"
                articles.append({
                    "id": a.xpath('.//a[@class="title"]')[0].attrib["href"][3:],
                    "title": a.xpath('.//a[@class="title"]')[0].text,
                    "summary": a.xpath('.//p[@class="abstract"]')[0].text.strip(),
                    "view": int(a.xpath('.//div[@class="meta"]/a[1]/text()')[1].strip()),
                    "imgSrc": img,
                    "time": a.xpath('.//span[@class="time"]')[0].attrib["data-shared-at"]
                })
        except IndexError:
            return None
        # return (count, page, articles)
        return articles

    def detail(self, article_id):
        r = requests.get("http://www.jianshu.com/p/" + article_id)
        if r.status_code == 404:
            return None
        html = etree.HTML(r.text)
        data = json.loads(html.xpath('//script[@data-name="page-data"]')[0].text)
        return {
            "title": html.xpath('//h1[@class="title"]')[0].text,
            "content": etree.tostring(
                html.xpath('//div[@class="show-content"]')[0],
                encoding='utf-8').decode("utf-8").strip(),
            "time": html.xpath('//span[@class="publish-time"]')[0].text,
            "wordage": data["note"]["public_wordage"],
            "tag": html.xpath('//a[@class="notebook"]/span')[0].text
        }
    
    def notebooks(self, page=1):
        r = requests.get(url="http://www.jianshu.com/users/%s/notebooks" % self.UID,
                         params={
                             "slug": self.UID,
                             "type": "manager",
                             "page": str(page),
                             "pre_page": "5"
                         },
                         headers={
                             "Accept": "application/json"
                         })
        if r.json().get("error"):
            return None
        else:
            return r.json()

if __name__ == "__main__":
    j = jianshu("f1b13122a132")
    print(j.article(1))
